package com.walker.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.walker.security.service.MyUserService;
import com.walker.security.util.MyPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private MyUserService myUserService;

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/js/**", "/css/**", "/images/**"); // 不做安全认证的URl
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll() // 放行跟目录
				.anyRequest().authenticated() // 其它需要认证
				.and().logout().permitAll() // 允许注销
				.and().formLogin(); // 允许表单登陆
		http.csrf().disable(); // 关闭csrf
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// super.configure(auth);
		// 示例1：基于内存的用户认证
		/*
		 * auth.inMemoryAuthentication().withUser("walker").password("2018").roles("ADMIN");
		 * auth.inMemoryAuthentication().withUser("demo").password("2018").roles("USER");
		 * 
		 */

		// 示例2：基于数据库的用户认证
		auth.userDetailsService(myUserService).passwordEncoder(new MyPasswordEncoder()); // 使用自定义userService 和密码加密规则

		auth.jdbcAuthentication().usersByUsernameQuery("") //用户查下SQL
				.authoritiesByUsernameQuery("")            //权限查下SQL
				.passwordEncoder(new MyPasswordEncoder());
	}

}
